import 'package:blurb/common/routers/names.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';
import '../../common/values/images.dart';
import '../../common/values/svg.dart';
import 'package:provider/provider.dart';
import '../../common/store/topic_store.dart';
import '../../common/models/topic.dart';
import '../../common/models/comment.dart';
import '../../common/store/user_store.dart';
import '../../common/models/user.dart';
import '../../common/services/user_service.dart';

class TopicDetailPage extends StatefulWidget {
  final int topicId;
  const TopicDetailPage({Key? key, required this.topicId}) : super(key: key);

  @override
  State<TopicDetailPage> createState() => _TopicDetailPageState();
}

class _TopicDetailPageState extends State<TopicDetailPage> {
  final TextEditingController _controller = TextEditingController();
  bool _isSending = false;

  Future<void> _sendComment(TopicStore topicStore, int userId) async {
    final userStore = Provider.of<UserStore>(context, listen: false);
    final currentUser = userStore.currentUser;
    
    if (currentUser == null) {
      // 用户未登录
      _showLoginDialog(context);
      return;
    }

    if (_controller.text.trim().isEmpty) return;
    setState(() => _isSending = true);
    final comment = Comment(
      id: DateTime.now().millisecondsSinceEpoch,
      content: _controller.text.trim(),
      time: DateTime.now().toIso8601String(),
      userId: userId,
      topicId: widget.topicId,
    );
    await topicStore.addComment(comment);
    _controller.clear();
    setState(() => _isSending = false);
    setState(() {});
  }

  String _formatTime(String isoTime) {
    final dt = DateTime.tryParse(isoTime);
    if (dt == null) return '';
    final diff = DateTime.now().difference(dt);
    if (diff.inDays > 0) return '${diff.inDays} days ago';
    if (diff.inHours > 0) return '${diff.inHours} hours ago';
    if (diff.inMinutes > 0) return '${diff.inMinutes} minutes ago';
    return 'just now';
  }

  Widget _buildCommentItem(Comment comment) {
    return FutureBuilder<User?>(
      future: UserService.getUserById(comment.userId),
      builder: (context, snapshot) {
        final user = snapshot.data;
        final userName = user?.nickname ?? 'user ${comment.userId}';
        final userAvatar = user?.avatar ?? MIP.avatar;
        return Padding(
          padding: EdgeInsets.symmetric(vertical: 12.h),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  CircleAvatar(
                    radius: 16.r,
                    backgroundImage: AssetImage(userAvatar),
                  ),
                  SizedBox(width: 8.w),
                  Text(
                    userName,
                    style: GoogleFonts.racingSansOne(
                      color: Colors.white,
                      fontSize: 16.sp,
                      fontWeight: FontWeight.normal,
                    ),
                  ),
                  SizedBox(width: 8.w),
                  Text(
                    _formatTime(comment.time),
                    style: GoogleFonts.inter(
                      color: Colors.grey,
                      fontSize: 12.sp,
                    ),
                  ),
                  Spacer(),
                  // Follow按钮
                  Container(
                    padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
                    decoration: BoxDecoration(
                      gradient: const LinearGradient(
                        begin: Alignment(0.50, 0.00),
                        end: Alignment(0.50, 0.96),
                        colors: [Color(0xFF60C3FF), Color(0xFFAADEFC)],
                      ),
                      borderRadius: BorderRadius.circular(37.r),
                    ),
                    child: Row(
                      children: [
                        Container(
                          width: 16.w,
                          height: 16.h,
                          decoration: BoxDecoration(
                            color: Colors.transparent,
                            borderRadius: BorderRadius.circular(12.r),
                            border: Border.all(color: Colors.white, width: 1.w),
                          ),
                          child: Icon(
                            Icons.favorite_border,
                            color: Colors.white,
                            size: 12.sp,
                          ),
                        ),
                        SizedBox(width: 4.w),
                        Text(
                          'Follow',
                          style: GoogleFonts.inter(
                            fontSize: 12.sp,
                            fontWeight: FontWeight.normal,
                            color: Colors.white,
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
              SizedBox(height: 8.h),
              Text(
                comment.content,
                style: GoogleFonts.inter(color: Colors.white, fontSize: 14),
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _buildDivider() {
    return Divider(color: Colors.grey.withOpacity(0.2), thickness: 0.5);
  }

  @override
  Widget build(BuildContext context) {
    final topicStore = Provider.of<TopicStore>(context);
    final userStore = Provider.of<UserStore>(context, listen: false);
    final userId = userStore.currentUser?.id ?? 0;
    final Topic? topic = topicStore.topics.firstWhere(
      (t) => t.id == widget.topicId,
      orElse: () => Topic(id: 0, title: 'unknown topic', description: '', userId: 0),
    );

    Widget commentList = FutureBuilder<List<Comment>>(
      future: topicStore.getTopicComments(widget.topicId),
      builder: (context, snapshot) {
        if (!snapshot.hasData) {
          return Center(child: CircularProgressIndicator());
        }
        final comments = snapshot.data!;
        if (comments.isEmpty) {
          return Padding(
            padding: EdgeInsets.symmetric(vertical: 16),
            child: Text('no comments', style: TextStyle(color: Colors.white70)),
          );
        }
        final reversed = comments.reversed.toList();
        return Column(
          children: reversed
              .map((c) => Column(children: [
                    _buildCommentItem(c),
                    _buildDivider(),
                  ]))
              .toList(),
        );
      },
    );

    Widget inputBar = Stack(
      children: [
        Container(
          height: 80.h,
          decoration: BoxDecoration(
            color: const Color(0xFF60C3FF),
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(32.r),
              topRight: Radius.circular(32.r),
            ),
          ),
        ),
        Positioned(
          top: 3.h,
          left: 0,
          right: 0,
          height: 78.h,
          child: Container(
            decoration: BoxDecoration(
              color: Colors.black,
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(30.r),
                topRight: Radius.circular(30.r),
              ),
            ),
            child: Row(
              children: [
                Expanded(
                  child: Container(
                    margin: EdgeInsets.symmetric(horizontal: 16.w),
                    padding: EdgeInsets.symmetric(horizontal: 16.w),
                    height: 44.h,
                    decoration: BoxDecoration(
                      color: Colors.grey.shade800,
                      borderRadius: BorderRadius.circular(22.r),
                    ),
                    child: TextField(
                      controller: _controller,
                      decoration: InputDecoration(
                        border: InputBorder.none,
                        hintText: 'Join the discussion',
                        hintStyle: TextStyle(color: Colors.grey),
                      ),
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                ),
                Container(
                  decoration: BoxDecoration(
                    gradient: const LinearGradient(
                      begin: Alignment(0.50, 0.00),
                      end: Alignment(0.50, 0.96),
                      colors: [Color(0xFF60C3FF), Color(0xFFAADEFC)],
                    ),
                    shape: BoxShape.circle,
                  ),
                  child: IconButton(
                    icon: _isSending
                        ? SizedBox(width: 20, height: 20, child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white))
                        : Icon(Icons.send, color: Colors.white),
                    onPressed: _isSending
                        ? null
                        : () => _sendComment(topicStore, userId),
                  ),
                ),
                SizedBox(width: 16.w),
              ],
            ),
          ),
        ),
      ],
    );

    return Scaffold(
      backgroundColor: const Color(0xFF1F1F21),
      body: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage(MIP.background),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: Column(
            children: [
              // 顶部导航栏
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    IconButton(
                      icon: const Icon(
                        Icons.arrow_back_ios,
                        color: Colors.white,
                      ),
                      onPressed: () => Navigator.of(context).pop(),
                    ),
                    Text(
                      'topic',
                      style: GoogleFonts.racingSansOne(
                        fontSize: 24.sp,
                        color: Colors.white,
                      ),
                    ),
                    IconButton(
                      icon: Icon(MSI.report, color: Colors.white),
                      onPressed: () {},
                    ),
                  ],
                ),
              ),
              // 内容区域
              Expanded(
                child: SingleChildScrollView(
                  child: Column(
                    children: [
                      // 标题卡片
                      Container(
                        margin: EdgeInsets.symmetric(
                          horizontal: 16.w,
                          vertical: 8.h,
                        ),
                        padding: EdgeInsets.all(16.w),
                        decoration: BoxDecoration(
                          color: const Color(0xFF85D3F5),
                          borderRadius: BorderRadius.circular(12.r),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Expanded(
                              child: Text(
                                topic?.title ?? '',
                                style: GoogleFonts.racingSansOne(
                                  fontSize: 20.sp,
                                  color: Colors.white,
                                ),
                              ),
                            ),
                            Icon(MSI.collection, color: Colors.white),
                          ],
                        ),
                      ),
                      // 话题内容
                      Container(
                        margin: EdgeInsets.symmetric(horizontal: 16.w),
                        padding: EdgeInsets.all(16.w),
                        decoration: BoxDecoration(
                          color: const Color(0xFF1F1F21),
                          borderRadius: BorderRadius.circular(12.r),
                        ),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              topic?.description ?? '',
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 16,
                              ),
                            ),
                            SizedBox(height: 24.h),
                            commentList,
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              inputBar,
            ],
          ),
        ),
      ),
    );
  }
  // 显示登录提示对话框
  void _showLoginDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        backgroundColor: const Color(0xFF1F1F21),
        title: Text(
          'Please login first',
          style: GoogleFonts.racingSansOne(
            color: Colors.white,
            fontSize: 24.sp,
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text(
              'Cancel',
              style: GoogleFonts.racingSansOne(
                color: Colors.white70,
                fontSize: 18.sp,
                fontWeight: FontWeight.normal,
              ),
            ),
          ),
          GestureDetector(
            onTap: () {
              GoRouter.of(context).push(RNS.guide);
            },
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 10.h),
              decoration: BoxDecoration(
                gradient: const LinearGradient(
                  begin: Alignment(0.50, 0.00),
                  end: Alignment(0.50, 0.96),
                  colors: [Color(0xFF60C3FF), Color(0xFFAADEFC)],
                ),
                borderRadius: BorderRadius.circular(30.r),
              ),
            child: Text(
              'Go to login',
              style: GoogleFonts.racingSansOne(
                color: Colors.white,
                fontSize: 18.sp,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}